package com.qc.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.qc.common.DateUtil;
import com.qc.entity.WeiXinEntity;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeiXin {
	
	
	public static void main(String[] args) {
		
		/*JSONObject json = WeiXin.getAccessToken();
		String access_token = json.getString("access_token");
		
		
		
		String urls = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
		JSONObject jsonObject1 = httpRequest(urls, "GET", new JSONObject());
        try {
            
        	//3、时间戳和随机字符串  
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串  
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳  

            String jsapi_ticket = jsonObject1.getString("ticket");
            String url = "http://192.168.1.22:8080/69mark/MobileGetSecScheduleBySsId2.do?ssId=4&screenWidth=414";
            
            String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url; 
            
			 try {  
			        MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");  
			        digest.update(str.getBytes());  
			        byte messageDigest[] = digest.digest();  
			        // Create Hex String  
			        StringBuffer hexString = new StringBuffer();  
			        // 字节数组转换为 十六进制 数  
			            for (int i = 0; i < messageDigest.length; i++) {  
			                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);  
			                if (shaHex.length() < 2) {  
			                    hexString.append(0);  
			                }  
			                hexString.append(shaHex);  
			            }  
			            
			            System.out.println(access_token);
			            System.out.println(jsapi_ticket);
			            System.out.println("********"+str);
			            System.out.println(noncestr);
						System.out.println(timestamp);
						System.out.println(hexString.toString());
			   
			        } catch (NoSuchAlgorithmException e) {  
			            e.printStackTrace();  
			        }   
            
        } catch (JSONException e) {
        }*/
		
		
		
		String t = "2017-04-10 13:49:57";
		
		/*SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		try {
			Date date = sdf2.parse(t);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
			String time = sdf1.format(date);
			System.out.println(time);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}*/
		
		try {
			if (WeiXin.time(DateUtil.stringFormat(t)) == false) {
				System.out.println(false);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	
	public static JSONObject getAccessToken(WeiXinEntity weiXinEntity){
		String appId = "wx470a62725a7dbf54";//"wx470a62725a7dbf54";
		String appSecret = "990d0d9a51cea0caeca1af64f3d27219";//"d8d77691c132e07af2a9a076974b4e24";
        
        String access_token = "";
        String expires_in = "";
        
        JSONObject jsonObject = new JSONObject();
        String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
        JSONObject jsonObject1 = httpRequest(getTokenUrl, "GET", jsonObject);
         if (null != jsonObject) {
             try {
                 access_token = jsonObject1.getString("access_token");
                 expires_in = jsonObject1.getString("expires_in");
             } catch (JSONException e) {
                 access_token = null;  
             }
         }
         
         JSONObject jsonObject2 = new JSONObject();
         jsonObject2.put("access_token", access_token);
         jsonObject2.put("expires_in", expires_in);
         jsonObject2.put("appId", appId);
         
         return jsonObject2;  
    }



	/** 
	 * 发起https请求并获取结果 
	 * @param requestUrl 请求地址 
	 * @param requestMethod 请求方式（GET、POST） 
	 * @param outputStr 提交的数据 
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
	 */ 
	public static JSONObject httpRequest(String requestUrl, String requestMethod, JSONObject outputStr) {  

       JSONObject jsonObject = null;  
       StringBuffer buffer = new StringBuffer();  

       try {  

           // 创建SSLContext对象，并使用我们指定的信任管理器初始化  
           TrustManager[] tm = { new WeixinX509TrustManager() };
           SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
           sslContext.init(null, tm, new java.security.SecureRandom());  
           // 从上述SSLContext对象中得到SSLSocketFactory对象  
           SSLSocketFactory ssf = sslContext.getSocketFactory();  
           URL url = new URL(requestUrl);  
           HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
           httpUrlConn.setSSLSocketFactory(ssf);  
           httpUrlConn.setDoOutput(true);  
           httpUrlConn.setDoInput(true);  
           httpUrlConn.setUseCaches(false);  
           // 设置请求方式（GET/POST）  
           httpUrlConn.setRequestMethod(requestMethod);  
           if ("GET".equalsIgnoreCase(requestMethod))  

               httpUrlConn.connect();  

           // 当有数据需要提交时  
           if (outputStr != null && null != outputStr.toString()) {  
               OutputStream outputStream = httpUrlConn.getOutputStream();  
               // 注意编码格式，防止中文乱码  
               outputStream.write(outputStr.toString().getBytes("UTF-8"));  
               outputStream.close();  
           }  

           // 将返回的输入流转换成字符串  
           InputStream inputStream = httpUrlConn.getInputStream();  
           InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
           BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
           String str = null;  
           while ((str = bufferedReader.readLine()) != null) {
               buffer.append(str);
           }  

           bufferedReader.close();
           inputStreamReader.close();
           // 释放资源  
           inputStream.close();  
           inputStream = null;
           httpUrlConn.disconnect();
           jsonObject = JSONObject.fromObject(buffer.toString());
                    
       } catch (ConnectException ce) {
          ce.printStackTrace();
       } catch (Exception e) {
           e.printStackTrace();
       }  
       return jsonObject;
	}
	
	
	
	public static boolean time(String tokenTime) throws ParseException{
		//获取当前系统时间
		long time2 = System.currentTimeMillis();
		Date date = new Date(time2);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		//获取2小时后的日期
        Date dt = dateFormat.parse(tokenTime.substring(0,14));
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.HOUR,2);//日期加10天
        Date dt1=rightNow.getTime();
        String reStr = dateFormat.format(dt1);
		String time = dateFormat.format(date);
        
        Date date2 = dateFormat.parse(reStr);
        Date date3 = dateFormat.parse(time);
        System.out.println(time);
        if ( date2.before(date3)) {
            System.out.println("xiaoyu");
            return false;
        }else{
            System.out.println("dayu");
            return true;
        }
        
	}
}
